package com.kiss.fw.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.http.HTTPException;

import org.apache.log4j.Logger;

import com.kiss.fw.utils.Util;

public abstract class AbstractFilter implements Filter {
	private static final Logger logger = Logger.getLogger(AbstractFilter.class);
	protected FilterConfig filterConfig;
	
	protected AbstractFilter() {
		super();
	}
	
	protected abstract void initialize() throws Exception;
	protected abstract void execute(HttpServletRequest _request, HttpServletResponse _response) throws Exception;
	
	@Override
	public final void destroy() {
		logger.info("destroy() - " +filterConfig.getFilterName());
		filterConfig = null;
	}
	
	@Override
	public final void init(final FilterConfig _filterConfig) throws ServletException {
		logger.info("init() - " +_filterConfig.getFilterName());
		filterConfig = _filterConfig;
		
		try {
			initialize();
		}
		catch(Exception _exception) {
			logger.error("init() - Error", _exception);
		}
	}
	
	public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain _chain) throws IOException, ServletException {
		final StringBuffer requestedUrl = getRequestedUrl(_request);
		int responseCode = 200;
		
		logger.debug(requestedUrl);
		
		HttpServletRequest request = getHttpServletRequest(_request);
		HttpServletResponse response = getHttpServletResponse(_response);
		
		try {
			execute(request, response);
		}
		catch(HTTPException _exception) {
			responseCode = _exception.getStatusCode();
		}
		catch(Throwable _throwable) {
			logger.error("Unknown and unexpected error occured in the filter, routing to error page", _throwable);
			responseCode = 500;
			_throwable = null;
		}
		
		if(responseCode != 200) {
			// if no error page is configured, just send the error code
			// and let the default handle (configured in web.xml)
			if(filterConfig.getInitParameter("errorPage") == null) {
				response.sendError(responseCode);
			}
			else {
				StringBuffer sb = new StringBuffer();
				sb.append(filterConfig.getInitParameter("errorPage"));
				sb.append("?code=");
				sb.append(responseCode);
				
				response.sendRedirect(sb.toString());
			}
		}
		else {
			_chain.doFilter(_request, _response);
		}
	}
	
	protected static HttpServletRequest getHttpServletRequest(final ServletRequest _request) {
		return (HttpServletRequest)_request;
	}
	
	protected static HttpServletResponse getHttpServletResponse(final ServletResponse _response) {
		return (HttpServletResponse)_response;
	}
	
	protected static StringBuffer getRequestedUrl(final ServletRequest _request) {
		return getHttpServletRequest(_request).getRequestURL();
	}
	
	protected static String getRequestedUri(final ServletRequest _request) {
		return getHttpServletRequest(_request).getRequestURI();
	}
	
	protected static boolean matchesRequestedUrl(final ServletRequest _request, final String _webpageUrlProperty) {
		return getRequestedUrl(_request).indexOf(Util.getProperty(_webpageUrlProperty)) >= 0;
	}
	
	protected static boolean isValidInput(final String _input, final String _validInputProperty) {
		boolean returnVal = false;
		
		if(!Util.containsSpecialCharacters(_input)) {
			returnVal = Util.containsToken(Util.getProperty(_validInputProperty), ",", _input, true);
		}
		
		return returnVal;
	}
}